<script setup name="music-detail">
import { computed, ref, watch, onMounted, reactive } from 'vue'
import { usePlayStore } from '@/stores'
import { storeToRefs } from 'pinia'
import { Vue3Marquee } from 'vue3-marquee'
import { showToast } from 'vant'
import { songComment } from '@/services/home'
import { artistDetail } from '@/services/singer'
import { useRouter } from 'vue-router'
import { formatSongSecond, formatSongTime, formartNum } from '@/utils/util'
import {
  Down,
  ShareThree,
  Like,
  Download,
  HandleRound,
  Message,
  MoreOne,
  ShuffleOne,
  PlayOnce,
  PlayCycle,
  GoStart,
  Play,
  MusicList,
  PauseOne,
  GoEnd
} from '@icon-park/vue-next'

import IconPark from '@/components/common/IconPark.vue'
import Lyrics from './Lyrics.vue'
import MinMusic from '@/components/MinMusic.vue'

const props = defineProps({
  curMusic: {
    type: Object
  },
  play: {
    type: Function
  },
  isPlayer: {
    type: Boolean
  },
  SongCurrentTime: {
    type: Number
  }
})

const router = useRouter()

const songinfo = reactive({
  CommentCount: 0,
  hotComments: [],
  avatar: []
})

const { changeMusicDialog, setPlayStatus } = usePlayStore()
const { isShowPopup, musicDialog } = storeToRefs(usePlayStore())
const playStore = usePlayStore()

// 播放/暂停图标
const playIcon = computed(() => (props.isPlayer ? Play : PauseOne))
// 显示歌词
const lyricShow = ref(false)
const infoRef = ref(null)
const isOverflowing = ref(false)
const chooseSinger = ref(false)
const showMore = ref(false)
const showHotComment = ref(true)

// 播放/暂停
const goPlay = (direction) => {
  setPlayStatus(true)
  emit('change-song', direction)
}

const emit = defineEmits(['setCurrTime', 'change-song'])
const progressPercentage = ref()
// 处理时间
watch(
  () => props.SongCurrentTime,
  newVal => {
    if (props.curMusic) progressPercentage.value = newVal / formatSongSecond(props.curMusic?.duration) * 100
  }
)

const handleChange = (e) => {
  const totalSeconds = props.curMusic?.duration.split(':')
  const minutes = parseInt(totalSeconds[0], 10)
  const seconds = parseInt(totalSeconds[1], 10)
  const totalDuration = minutes * 60 + seconds
  const newTime = (e / 100) * totalDuration
  emit('setCurrTime', newTime)
}

const playerMode = [
  { model: "顺序播放", icon: PlayCycle },
  { model: "单曲循环", icon: PlayOnce },
  { model: "随机播放", icon: ShuffleOne }
]
// 0: 顺序播放，1: 循环播放，2: 随机播放
const mode = ref(0)
// 当前播放模式
const modeText = computed(() => playerMode[playStore.info.playMode])

// 更改播放模式
const toggleMode = () => {
  mode.value === 2 ? mode.value = 0 : mode.value++
  // 修改 store 中的 playMode
  playStore.info.playMode = mode.value
  // 保持 mode.value 和 playStore.info.playMode 同步
  mode.value = playStore.info.playMode
  // 弹窗提醒
  showToast(modeText.value.model)
}

const handleShowMusic = () => playStore.setShowPopup(!isShowPopup.value)

onMounted(() => {
  isOverflow(infoRef.value)
  getSongCommentCount(props.curMusic?.id)
  if (props.curMusic?.duration) progressPercentage.value = props.SongCurrentTime / formatSongSecond(props.curMusic?.duration) * 100
})

const getSongCommentCount = async id => {
  const res = await songComment(id)
  songinfo.CommentCount = res.total
  songinfo.hotComments = res.hotComments
}

const isOverflow = el => {
  if (el) {
    isOverflowing.value = el.offsetHeight < el.scrollHeight || el.offsetWidth < el.scrollWidth
  }
}

const toSingerDetail = id => {
  changeMusicDialog()
  router.push({
    path: '/singer/detail',
    query: { id }
  })
  chooseSinger.value = false
}

const selectSinger = () => {
  if (props.curMusic?.singer.length > 1) {
    chooseSinger.value = true
    getSingerAvatar()
  } else {
    toSingerDetail(props.curMusic?.singer[0].id)
  }
}

const getSingerAvatar = () => {
  props.curMusic?.singer.forEach(async item => {
    const { data } = await artistDetail(item.id)
    songinfo.avatar.push(data.artist.avatar)
  })
}

const handleshowMore = () => {
  showMore.value = !showMore.value
}

watch(
  () => props.curMusic?.id,
  async newVal => {
    await getSongCommentCount(newVal)
    isOverflow(infoRef.value)
    getSingerAvatar()
  }
)

window.addEventListener('beforeunload', () => localStorage.setItem('SongCurrentTime', props.SongCurrentTime.toString()))
</script>

<template>
  <van-popup style="height: 100vh" v-model:show="musicDialog" position="bottom">
    <div class="music-detail">
      <!-- 热评 -->
      <div class="music-detail-hotComment" v-if="songinfo.hotComments && showHotComment">
        <van-button size="mini" round color="#45444323" class="transparentBtn">
          <van-swipe vertical class="notice-swipe" :autoplay="4000" :touchable="false" :show-indicators="false">
            <van-swipe-item v-for="item in songinfo?.hotComments" :key="item.commentId">
              <div class="content">
                <van-image width="22px" height="22px" round :src="item.user.avatarUrl" />
                <div class="van-ellipsis item">{{ item.content }}</div>
              </div>
            </van-swipe-item>
          </van-swipe>
        </van-button>
      </div>

      <img class="bgImg" :src="`${curMusic?.album.picUrl}?param=390y500`" />

      <div class="music-detail-header">
        <van-row gutter="24" justify="center">
          <van-col span="4">
            <div class="music-detail-header-back">
              <IconPark :icon="Down" :strokeWidth="2" :size="8" @click="changeMusicDialog" />
            </div>
          </van-col>

          <van-col span="14">
            <div class="music-detail-header-info" ref="infoRef">
              <Vue3Marquee v-if="isOverflowing" :delay="5">{{ curMusic?.name }}</Vue3Marquee>
              <span v-else>{{ curMusic?.name }}</span>
              <div class="music-detail-header-info-author" @click="selectSinger">
                <span v-for="(item, index) in curMusic?.singer" :key="index">
                  {{ item.name }}
                  <span v-if="index !== curMusic?.singer.length - 1"> & </span>
                </span>
              </div>
            </div>
          </van-col>

          <van-col span="6">
            <div class="music-detail-header-share">
              <IconPark :icon="ShareThree" :strokeWidth="2" :size="6" />
            </div>
          </van-col>
        </van-row>
      </div>

      <div class="music-detail-main" v-show="!lyricShow" @click="() => lyricShow = !lyricShow">
        <img class="music-detail-main-disc" src="@/assets/img/disc_bg.png" />
        <img class="music-detail-main-stylus" :class="{ 'music-detail-main-stylus-active': !isPlayer }"
          src="@/assets/img/stylus.png" />
        <van-image v-if="curMusic.album.picUrl" :src="curMusic?.album.picUrl"
          :class="{ 'cd-Rotate-Play': !isPlayer, 'cd-Rotate-Pause': isPlayer }" />
        <img v-else class="van-image" :class="{ 'cd-Rotate-Play': !isPlayer, 'cd-Rotate-Pause': isPlayer }"
          src="@/assets/img/disc.png">
      </div>

      <!-- <Lyrics @click="() => lyricShow = !lyricShow" v-show="lyricShow" :sId="Number(curMusic?.id)" :currentTime="currentTime" /> -->
      <Lyrics @click="() => lyricShow = !lyricShow" v-show="lyricShow" :sId="Number(curMusic?.id)"
        :currentTime="SongCurrentTime" />
      <!-- 收藏、下载、唱、评论、更多 -->
      <div class="music-detail-footer">
        <div class="music-detail-footer-actions">
          <van-row gutter="20" justify="center" align="center">
            <van-col span="4">
              <IconPark :icon="Like" :strokeWidth="2" :size="6" />
            </van-col>
            <van-col span="4">
              <IconPark :icon="Download" :strokeWidth="2" :size="6" />
            </van-col>
            <van-col span="4">
              <IconPark :icon="HandleRound" :strokeWidth="2" :size="6" />
            </van-col>
            <van-col span="4">
              <span class="music-detail-footer-actions-comment">{{ formartNum(songinfo.CommentCount) }}</span>
              <IconPark :icon="Message" :strokeWidth="2" :size="6" />
            </van-col>
            <van-col span="4" @click="handleshowMore">
              <IconPark :icon="MoreOne" :strokeWidth="2" :size="6" />
            </van-col>
          </van-row>
        </div>
        <!-- 歌曲进度信息 -->
        <div class="music-detail-footer-schedule">
          <!-- <span class="song-time">{{ formatSongTime(currentTime * 1000) }}</span> -->
          <span class="song-time">{{ formatSongTime(SongCurrentTime * 1000) }}</span>
          <van-slider v-model="progressPercentage" @change="handleChange">
            <template #button>
              <div class="custom-button"></div>
            </template>
          </van-slider>
          <span class="song-time">{{ curMusic?.duration }}</span>
        </div>
        <!-- 播放操作 -->
        <div class="music-detail-footer-played">
          <van-row gutter="20" justify="center">
            <van-col span="4">
              <div class="icon">
                <IconPark :icon="modeText.icon" :strokeWidth="3" :size="6" @click="toggleMode" />
              </div>
            </van-col>
            <van-col span="4">
              <div class="icon">
                <IconPark :icon="GoStart" :strokeWidth="4" :size="8" @click="goPlay('prev')" />
              </div>
            </van-col>
            <van-col span="4">
              <IconPark :icon="playIcon" :strokeWidth="1" :size="18" @click="play" />
            </van-col>
            <van-col span="4">
              <div class="icon">
                <IconPark :icon="GoEnd" :strokeWidth="4" :size="8" @click="goPlay('next')" />
              </div>
            </van-col>
            <van-col span="4">
              <div class="icon">
                <IconPark :icon="MusicList" :strokeWidth="2" :size="8" theme="filled" @click="handleShowMusic" />
              </div>
            </van-col>
          </van-row>
        </div>
      </div>
      <MinMusic />
      <van-popup round v-model:show="chooseSinger" position="bottom">
        <van-row gutter="24" justify="center">
          <van-col span="22">
            <span class="title">该歌曲有多个歌手</span>
          </van-col>
          <van-col span="24">
            <van-row class="singer-info" gutter="20" justify="center" v-for="(item, index) in curMusic.singer"
              :key="item.id" @click="toSingerDetail(item.id)">
              <van-col span="3" class="singer-info-col">
                <van-image radius="10%" width="40" :src="songinfo.avatar[index]" />
              </van-col>
              <van-col span="15" class="singer-info-col">
                {{ item.name }}
              </van-col>
              <van-col span="5" class="singer-info-col">
                <van-button icon="plus" size="small" round plain color="#ff3534" hairline
                  style="background: transparent; height: 24px;">关注</van-button>
              </van-col>
            </van-row>
          </van-col>
        </van-row>
      </van-popup>
      <van-action-sheet v-model:show="showMore" :description="curMusic.name">
        <van-row gutter="24" justify="center">
          <van-col span="18">
            {{ showHotComment ? '显示热评' : '关闭热评' }}
          </van-col>
          <van-col span="4">
            <van-switch v-model="showHotComment" size="20px" inactive-color="#ee0a24">
              <template #node>
                <div class="icon-wrapper">
                  <van-icon :name="showHotComment ? 'success' : 'cross'" />
                </div>
              </template>
            </van-switch>
          </van-col>
        </van-row>
      </van-action-sheet>
    </div>
  </van-popup>
</template>

<style scoped lang="scss">
.music-detail {
  color: var(--vt-c-white);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100vh;

  .i-icon {
    cursor: pointer;
  }

  &-hotComment {
    position: absolute;
    top: 60px;
    left: 8%;
    background-color: transparent;

    .notice-swipe {
      width: 80vw;
      height: 20px;
      line-height: 20px;

      .content {
        display: flex;
        align-items: center;
        text-align: left;
        line-height: 1;
        height: 100%;

        .van-image {
          margin-right: 4px;
        }

        .item {
          width: 100%;
          overflow: hidden;
        }
      }

    }
  }

  &-header {
    padding: 10px 6px;
    line-height: 18px;

    &-back,
    &-share {
      display: flex;
      justify-content: center;
    }

    &-info {
      display: flex;
      flex-direction: column;
      align-items: center;
      text-align: center;
      width: 120px;
      margin: auto;
      white-space: nowrap;
      overflow: hidden;

      h4 {
        width: 120px;
      }

      &-author {
        font-size: 13px;
        color: #b0b6ba;
        margin-top: 8px;
        cursor: pointer;
      }
    }
  }

  &-main {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;

    &-disc {
      width: 300px;
      height: 300px;
      z-index: 1;
      cursor: pointer;
    }

    &-stylus {
      width: 30px;
      height: 140px;
      position: absolute;
      left: 64%;
      top: 1%;
      transform-origin: 23px 5px;
      transform: rotate(-46deg);
      transition: all 1s;
      z-index: 1;
    }

    &-stylus-active {
      transform: rotate(-28deg);
      transition: all 0.6s;
    }

    .van-image {
      width: 190px;
      height: 190px;
      position: absolute;
      top: 18%;
      animation: rotateZ 15s linear infinite;
    }

    .cd-Rotate-Play {
      animation-play-state: running;
    }

    .cd-Rotate-Pause {
      animation-play-state: paused;
    }

    @keyframes rotateZ {
      0% {
        transform: rotate(0deg);
      }

      100% {
        transform: rotate(360deg);
      }
    }
  }

  &-footer {
    line-height: 1;

    &::after {
      content: '';
      height: 100%;
      width: 100%;
      background: linear-gradient(black, transparent, transparent, black);
      position: absolute;
      bottom: 0;
      z-index: -1;
    }

    &-schedule {
      padding: 0 16px;
      height: 40px;
      display: flex;
      align-items: center;

      :deep(.van-slider__bar) {
        background-color: #ffffff94;
      }

      .van-slider {
        background-color: #ffffff3d;
        margin: 0 8px;
        height: 3px;
      }

      .song-time {
        font-size: 8px;
        color: #ffffff3d;
        display: inline-block;
        width: 34px;
      }

      .custom-button {
        width: 8px;
        height: 8px;
        color: #fff;
        font-size: 10px;
        line-height: 18px;
        text-align: center;
        background-color: var(--vt-c-white);
        border-radius: 100px;
      }
    }

    &-actions {
      margin-bottom: 20px;

      .van-col--4 {
        display: flex;
        justify-content: center;
        position: relative;

      }

      &-comment {
        display: inline-block;
        text-align: center;
        width: 36px;
        height: 16px;
        line-height: 14px;
        padding: 2px;
        background-color: #928a873a;
        backdrop-filter: blur(12px);
        border-radius: 20%;
        transform: scale(0.85);
        position: absolute;
        top: 5px;
        right: 2px;
        font-size: 10px;
      }
    }

    &-played {
      .van-col--4 {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-bottom: 40px;
      }
    }
  }

  :deep(.van-popup--round) {
    background-color: var(--color-background);
    color: var(--reversal-text);
    padding: 10px 0;

    .title {
      font-size: 10px;
    }

    .singer-info {
      padding: 4px 0;

      &-col {
        display: flex;
        align-items: center;
      }
    }
  }
}

.bgImg {
  width: 100%;
  position: absolute;
  top: 120px;
  z-index: -1;
  filter: blur(40px);
  max-width: 390px;
}

.icon-wrapper {
  display: flex;
  width: 100%;
  justify-content: center;
  font-size: 18px;
}

.icon-wrapper .van-icon-success {
  line-height: 22px;
  color: var(--van-blue);
}

.icon-wrapper .van-icon-cross {
  line-height: 22px;
  color: #ee0a24;
}
</style>
